import datetime
import json
import os

class MembershipSystem:
    """会员等级评定系统"""
    
    def __init__(self):
        self.membership_data = []
        self.load_data()
    
    def determine_membership_level(self, consumption, points):
        """
        根据消费金额和积分确定会员等级
        
        参数:
        consumption (float): 消费金额（元）
        points (int): 积分
        
        返回:
        str: 会员等级名称
        """
        if consumption >= 1000 or points >= 5000:
            return "钻石会员"
        elif consumption >= 500 or points >= 2000:
            return "白金会员"
        elif consumption >= 200 or points >= 1000:
            return "黄金会员"
        elif consumption >= 100 or points >= 500:
            return "青铜会员"
        else:
            return "普通会员"
    
    def get_membership_requirements(self):
        """
        获取各会员等级的要求
        
        返回:
        dict: 包含各等级要求的字典
        """
        return {
            "钻石会员": {"消费金额": "≥ 1000元", "积分": "≥ 5000分"},
            "白金会员": {"消费金额": "≥ 500元", "积分": "≥ 2000分"},
            "黄金会员": {"消费金额": "≥ 200元", "积分": "≥ 1000分"},
            "青铜会员": {"消费金额": "≥ 100元", "积分": "≥ 500分"},
            "普通会员": {"消费金额": "< 100元", "积分": "< 500分"}
        }
    
    def calculate_next_level_progress(self, consumption, points, current_level):
        """
        计算距离下一等级还需要的消费金额或积分
        
        参数:
        consumption (float): 当前消费金额
        points (int): 当前积分
        current_level (str): 当前会员等级
        
        返回:
        dict: 包含距离下一等级所需的消费金额和积分
        """
        requirements = self.get_membership_requirements()
        levels = list(requirements.keys())
        current_index = levels.index(current_level) if current_level in levels else -1
        
        if current_index == 0 or current_index == -1:  # 已经是最高等级或等级不存在
            return None
        
        next_level = levels[current_index - 1]
        next_requirements = requirements[next_level]
        
        # 解析下一下一等级的要求（提取数字部分）
        def extract_number(text):
            """从包含符号的字符串中提取数字"""
            import re
            match = re.search(r'\d+', text)
            return int(match.group()) if match else 0
        
        next_consumption = extract_number(next_requirements["消费金额"])
        next_points = extract_number(next_requirements["积分"])
        
        # 计算还需要的消费金额和积分
        need_consumption = max(0, next_consumption - consumption)
        need_points = max(0, next_points - points)
        
        return {
            "next_level": next_level,
            "need_consumption": need_consumption,
            "need_points": need_points
        }
    
    def add_member(self, name, consumption, points):
        """
        添加会员记录
        
        参数:
        name (str): 会员姓名
        consumption (float): 消费金额
        points (int): 积分
        
        返回:
        dict: 会员信息字典
        """
        level = self.determine_membership_level(consumption, points)
        member = {
            "id": len(self.membership_data) + 1,
            "name": name,
            "consumption": consumption,
            "points": points,
            "level": level,
            "rating_date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        self.membership_data.append(member)
        self.save_data()
        return member
    
    def batch_add_members(self, members_list):
        """
        批量添加会员
        
        参数:
        members_list (list): 会员列表，每个元素是包含name, consumption, points的元组
        
        返回:
        list: 添加成功的会员信息列表
        """
        added_members = []
        for member_info in members_list:
            if len(member_info) >= 3:
                name, consumption, points = member_info[0], float(member_info[1]), int(member_info[2])
                member = self.add_member(name, consumption, points)
                added_members.append(member)
        return added_members
    
    def get_member_by_id(self, member_id):
        """
        根据ID获取会员信息
        
        参数:
        member_id (int): 会员ID
        
        返回:
        dict or None: 会员信息或None
        """
        for member in self.membership_data:
            if member["id"] == member_id:
                return member
        return None
    
    def get_members_by_level(self, level):
        """
        根据等级获取会员列表
        
        参数:
        level (str): 会员等级
        
        返回:
        list: 会员列表
        """
        return [member for member in self.membership_data if member["level"] == level]
    
    def save_data(self):
        """保存会员数据到文件"""
        try:
            with open("membership_data.json", "w", encoding="utf-8") as f:
                json.dump(self.membership_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存数据失败: {e}")
            return False
    
    def load_data(self):
        """从文件加载会员数据"""
        try:
            if os.path.exists("membership_data.json"):
                with open("membership_data.json", "r", encoding="utf-8") as f:
                    self.membership_data = json.load(f)
            return True
        except Exception as e:
            print(f"加载数据失败: {e}")
            self.membership_data = []
            return False
    
    def display_member_info(self, member):
        """
        显示会员详细信息
        
        参数:
        member (dict): 会员信息字典
        """
        if not member:
            print("未找到会员信息")
            return
        
        print("=" * 60)
        print(f"会员ID: {member['id']}")
        print(f"姓名: {member['name']}")
        print(f"消费金额: {member['consumption']:.2f}元")
        print(f"积分: {member['points']}分")
        print(f"会员等级: {member['level']}")
        print(f"评定日期: {member['rating_date']}")
        
        # 显示升级进度
        progress = self.calculate_next_level_progress(
            member['consumption'], member['points'], member['level'])
        
        if progress:
            print(f"\n升级进度:")
            print(f"距离{progress['next_level']}还需:")
            if progress['need_consumption'] > 0:
                print(f"  - 消费金额: {progress['need_consumption']:.2f}元")
            if progress['need_points'] > 0:
                print(f"  - 积分: {progress['need_points']}分")
            print(f"（满足任一条件即可升级）")
        else:
            print(f"\n恭喜！您已是最高等级的会员。")
        
        print("=" * 60)
    
    def display_all_members(self):
        """显示所有会员信息"""
        if not self.membership_data:
            print("暂无会员记录")
            return
        
        print("=" * 80)
        print(f"{'ID':<4} {'姓名':<10} {'消费金额':<10} {'积分':<8} {'等级':<8} {'评定日期':<16}")
        print("-" * 80)
        
        for member in self.membership_data:
            print(f"{member['id']:<4} {member['name']:<10} {member['consumption']:<10.2f} "
                  f"{member['points']:<8} {member['level']:<8} {member['rating_date']:<16}")
        
        print("-" * 80)
        print(f"总计: {len(self.membership_data)} 名会员")
        
        # 统计各等级会员数量
        level_stats = {}
        for member in self.membership_data:
            level_stats[member['level']] = level_stats.get(member['level'], 0) + 1
        
        print(f"\n等级分布:")
        for level, count in level_stats.items():
            percentage = (count / len(self.membership_data)) * 100
            print(f"  {level}: {count}人 ({percentage:.1f}%)")
        
        print("=" * 80)
    
    def display_level_requirements(self):
        """显示各等级要求"""
        print("=" * 60)
        print("会员等级要求")
        print("=" * 60)
        
        requirements = self.get_membership_requirements()
        for level, req in requirements.items():
            print(f"{level}:")
            print(f"  消费金额: {req['消费金额']}")
            print(f"  积分: {req['积分']}")
            print()
        
        print("注：满足消费金额或积分任一条件即可升级到对应等级")
        print("=" * 60)

def main():
    """主函数"""
    system = MembershipSystem()
    
    while True:
        print("\n" + "=" * 60)
        print("会员等级评定系统")
        print("=" * 60)
        print("1. 单个会员评定")
        print("2. 批量会员评定")
        print("3. 查询会员信息")
        print("4. 显示所有会员")
        print("5. 显示等级要求")
        print("0. 退出系统")
        print("=" * 60)
        
        choice = input("请选择操作: ")
        
        if choice == "1":
            # 单个会员评定
            try:
                name = input("请输入会员姓名: ")
                consumption = float(input("请输入消费金额（元）: "))
                points = int(input("请输入积分: "))
                
                if consumption < 0 or points < 0:
                    print("输入错误！消费金额和积分不能为负数。")
                    continue
                
                member = system.add_member(name, consumption, points)
                print(f"\n会员 {name} 评定成功！")
                system.display_member_info(member)
                
            except ValueError:
                print("输入错误！请输入有效的数字。")
            except Exception as e:
                print(f"操作失败: {e}")
        
        elif choice == "2":
            # 批量会员评定
            print("批量会员评定")
            print("请按照格式输入会员信息（姓名,消费金额,积分），每行一条，输入空行结束:")
            
            members_list = []
            while True:
                line = input()
                if not line.strip():
                    break
                
                try:
                    parts = line.strip().split(",")
                    if len(parts) >= 3:
                        name = parts[0].strip()
                        consumption = float(parts[1].strip())
                        points = int(parts[2].strip())
                        members_list.append((name, consumption, points))
                except:
                    print(f"格式错误: {line}，跳过此行")
            
            if members_list:
                added_members = system.batch_add_members(members_list)
                print(f"\n批量添加完成！成功添加 {len(added_members)} 名会员。")
                
                # 显示添加结果统计
                level_stats = {}
                for member in added_members:
                    level_stats[member['level']] = level_stats.get(member['level'], 0) + 1
                
                print("添加结果统计:")
                for level, count in level_stats.items():
                    print(f"  {level}: {count}人")
            else:
                print("未添加任何会员。")
        
        elif choice == "3":
            # 查询会员信息
            print("会员查询")
            print("1. 按ID查询")
            print("2. 按等级查询")
            query_choice = input("请选择查询方式: ")
            
            if query_choice == "1":
                try:
                    member_id = int(input("请输入会员ID: "))
                    member = system.get_member_by_id(member_id)
                    system.display_member_info(member)
                except ValueError:
                    print("输入错误！请输入有效的数字ID。")
            
            elif query_choice == "2":
                print("请选择会员等级:")
                requirements = system.get_membership_requirements()
                for i, level in enumerate(requirements.keys(), 1):
                    print(f"{i}. {level}")
                
                try:
                    level_index = int(input("请选择等级编号: ")) - 1
                    if 0 <= level_index < len(requirements):
                        level = list(requirements.keys())[level_index]
                        members = system.get_members_by_level(level)
                        
                        if members:
                            print(f"\n{level} 会员列表（共{len(members)}人）:")
                            print("-" * 80)
                            print(f"{'ID':<4} {'姓名':<10} {'消费金额':<10} {'积分':<8} {'评定日期':<16}")
                            print("-" * 80)
                            
                            for member in members:
                                print(f"{member['id']:<4} {member['name']:<10} {member['consumption']:<10.2f} "
                                      f"{member['points']:<8} {member['rating_date']:<16}")
                            
                            print("-" * 80)
                        else:
                            print(f"\n暂无{level}会员记录。")
                    else:
                        print("输入错误！请选择有效的等级编号。")
                except ValueError:
                    print("输入错误！请输入有效的数字。")
        
        elif choice == "4":
            # 显示所有会员
            system.display_all_members()
        
        elif choice == "5":
            # 显示等级要求
            system.display_level_requirements()
        
        elif choice == "0":
            # 退出系统
            print("感谢使用会员等级评定系统！")
            break
        
        else:
            print("输入错误！请选择有效的操作。")
        
        # 按任意键继续
        input("\n按回车键继续...")

if __name__ == "__main__":
    main()
